import { request } from '@umijs/max';
import type { SortOrder } from 'antd/es/table/interface';

export interface ProductItem {
  id: number;
  name: string;
  merchant: string;
  price: number;
  image: string;
  sales: number;
  description: string;
  type: string;
}

export interface ResponseData<T> {
  data: T;
  success: boolean;
  errorMessage?: string;
}

export interface ProductListParams {
  current?: number;
  pageSize?: number;
  keyword?: string;
  sortField?: string;
  sortOrder?: SortOrder;
  [key: string]: any;
}

export const ProductList = async (params?: ProductListParams) => {
  try {
    return await request<
      ResponseData<{ product: ProductItem[]; total: number }>
    >('/api/product/list', {
      method: 'GET',
      params,
    });
  } catch (error) {
    return {
      data: { product: [], total: 0 },
      success: false,
      errorMessage: '获取商品列表失败',
    };
  }
};

export const addProduct = async (params: Omit<ProductItem, 'id' | 'sales'>) => {
  try {
    return await request<ResponseData<{ id: number }>>('/api/product/add', {
      method: 'POST',
      data: params,
    });
  } catch (error) {
    return {
      data: { id: 0 },
      success: false,
      errorMessage: '添加商品失败',
    };
  }
};

export const updateProduct = async (
  params: Partial<ProductItem> & { id: number },
) => {
  try {
    return await request<ResponseData<{ success: boolean }>>(
      '/api/product/update',
      {
        method: 'PUT',
        data: params,
      },
    );
  } catch (error) {
    return {
      data: { success: false },
      success: false,
      errorMessage: '更新商品失败',
    };
  }
};

export const deleteProduct = async (id: number) => {
  try {
    return await request<ResponseData<{ success: boolean }>>(
      '/api/product/delete/' + id,
      {
        method: 'DELETE',
      },
    );
  } catch (error) {
    return {
      data: { success: false },
      success: false,
      errorMessage: '删除商品失败',
    };
  }
};
